# -*- coding: utf-8 -*-
#import cgi
import os
import json
import time
from datetime import datetime
import subprocess,sys

watchname="getgeoaddr.py"

def adjust():
	h=datetime.now().hour
	if(h>=0 and h<=6) or (h>=20 and h<=23):
		timeallow=7200
		timecheck=3600
	else:
		timeallow=1200
		timecheck=600
	return (timeallow,timecheck)

def readlog():
	logfilename=datetime.strftime(datetime.now(),"%Y%m%d")+".log"
	try:
		f=open('log'+os.sep+'getgeoaddr'+os.sep+logfilename,'r')
		try:
			return f.readlines()[-1].replace('\n','')
		finally:
			f.close()
	except IOError:
		pass
def calctimediff(timeallow):
	try:
		lasttime=datetime.strptime(readlog(), '%Y/%m/%d %H:%M:%S')
		timediff=(datetime.now() - lasttime).seconds
		if timediff>timeallow:
			return True
		else:
			return False
	except:
		return False
p=subprocess.Popen(['python.exe',watchname]) 
while True:
	time.sleep(adjust()[1])
	try:
		ret=subprocess.Popen.poll(p)
	except:
		p.terminate()
		time.sleep(5)
		p=subprocess.Popen(['python.exe',watchname]) 
	#print p.pid,ret,calctimediff()
	if calctimediff(adjust()[0]) and (ret is None):
		p.terminate()
		time.sleep(5)
		p=subprocess.Popen(['python.exe',watchname]) 
	
